package com.back.security;

import com.back.common.utils.GsonUtil;
import com.back.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义访问拒绝处理器
 * 当用户尝试访问没有权限的资源时，返回友好的JSON错误信息
 */
@Component
@Slf4j
public class RoleBasedAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, 
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        
        // 记录访问被拒绝的信息
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            log.warn("用户: {} 尝试访问未授权资源: {}", auth.getName(), request.getRequestURI());
        }
        
        // 设置响应状态和内容类型
        response.setStatus(HttpStatus.SC_FORBIDDEN);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        
        // 构建错误响应
        Result result = Result.error()
                .code(HttpStatus.SC_FORBIDDEN)
                .message("您没有权限访问该资源");
        
        // 写入响应体
        try (PrintWriter writer = response.getWriter()) {
            writer.write(GsonUtil.toJson(result));
            writer.flush();
        }
    }
} 